02. Operators in Playgrounds

Let’s plug the totalPoints example into a Playground.

The "totalPoints" calculation can be translated almost directly into a Playground.

The "totalPoints" calculation can be translated almost directly into a Playground.

Here, we have our variables declared and the calculation is returning the value 1320 as expected. Note: I have hard-coded the randomBonus to always return 20—but that is not the default behavior. Normally, it should return a random value between 0 and 100.

Breaking it Down

We'll split up the calculation into individual statements to see the operators one-at-a-time.

Splitting the calculation into multiple lines gives us better visibility of intermediate values.

Splitting the calculation into multiple lines gives us better visibility of intermediate values.

We've added a calculation for determining the lifeBonus based on the numberOfLives multiplied by pointsPerLife. Similarly, we've added a calculation for the deathBonus. We use both the lifeBonus and deathBonus in the final calculation which is stored into newTotalPoints. The purpose of splitting these calculations up is to demonstrate that the operators—addition (+), subtraction (-), and multiplication (*)—work as you would expect mathematically.

Order of Operations

Now when I say “the operators work as you expect mathematically”, I am talking about the order in which the operators are applied. (Caution: Content may cause flashbacks to elemenatary school lessons.)

The mathematical order of operations applies for the operators in this calculation.

The mathematical order of operations applies for the operators in this calculation.

Order of Operations

In this case, since all the operators are your standard mathematical operators, they are applied using the standard mathematical order of operations. But once we start using operators that aren’t from your standard math class, the order of operations may be different than what you expect.